<?php

/**
 * Description of StringFunctions
 *
 * @author a.novikov
 */
class StringFunctions {

	const KEY = 'zubrobobr';

	public static function composite($kernel, $prefix = '', $suffix = '') {
		return $prefix.$kernel.$suffix;
	}

	public static function camelCaseToUnderscore($name) {
		$filter = new Zend_Filter_Word_CamelCaseToUnderscore();
		return $filter->filter($name);
	}

	public static function underscoreToCamelCase($name) {
		$filter = new Zend_Filter_Word_UnderscoreToCamelCase();
		return $filter->filter($name);
	}

	public static function underscoreToCamelCaseComposite($name, $prefix = '', $suffix = '') {
		$name = self::underscoreToCamelCase($name);
		return self::composite($name, $prefix, $suffix);
	}

	/**
	 *
	 * @param string $str
	 * @return string
	 */
	public static function lcfirst($str) {
		$str = (string)$str;
		$str[0] = strtolower($str[0]);
		return $str;
	}

	/**
	 *
	 * @param string $str
	 * @param string $prefix
	 * @param string $suffix
	 * @return string
	 */
	public static function lcfirstComposite($str, $prefix = '', $suffix = '') {
		$str = self::lcfirst($str);
		return self::composite($str, $prefix, $suffix);
	}

	/**
	 *
	 * @param string $str
	 * @return string
	 */
	public static function ucfirst($str) {
		return ucfirst($str);
	}

	/**
	 *
	 * @param string $str
	 * @param string $prefix
	 * @param string $suffix
	 * @return string
	 */
	public static function ucfirstComposite($str, $prefix = '', $suffix = '') {
		$str = self::ucfirst($str);
		return self::composite($str, $prefix, $suffix);
	}

	/**
	 *
	 * @param array $params
	 * @return string
	 */
	public static function makeUrl(array $params) {
		return Zend_Controller_Front::getInstance()->getRouter()->assemble($params, null, true);
	}
	
	/**
	 *
	 * @param string $color
	 * @return string
	 */
	public static function getCssColor($color) {
		return $color;
//		return sprintf('#%06X', $colorNumber );
	}

	/**
	 *
	 * @param int $price
	 * @param string $delimiter
	 * @return string
	 */
	public static function partPrice($price, $delimiter = '&nbsp;') {
		return str_replace(',', $delimiter, number_format((int)$price, 0));
	}
	
	/**
	 *
	 * @param string $str
	 * @return string
	 */
	public static function translit($str)
	{
		$str = self::replaceSpecialChars($str);
		// Сначала заменяем "односимвольные" фонемы.
		$str = iconv('UTF-8', 'CP1251', $str);

		$rus_low = iconv('UTF-8', 'CP1251', "абвгдеёзийклмнопрстуфхъыэ");
		$rus_hi = iconv('UTF-8', 'CP1251', "АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ");
		$str=strtr($str,$rus_low, "abvgdeeziiklmnoprstufhiye");
		$str=strtr($str,$rus_hi,     "ABVGDEEZIIKLMNOPRSTUFHIYE");
		// Затем - "многосимвольные".

		$arr =
		        array(
		                "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
		                "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
		                "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
		                "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
		                "ї"=>"i", "Ї"=>"Yi", "є"=>"ie", "Є"=>"Ye",
		        );
		$arr_result = array();
		foreach ($arr as $ru => $eng) {
			$arr_result[iconv('UTF-8', 'CP1251', $ru)] = $eng;
		}
		$str=strtr($str, $arr_result);
		// Возвращаем результат.
		return iconv('CP1251', 'UTF-8', $str);
	}

	public static function replaceSpecialChars($string) {
	    $src = array(
	       'ö'
	    );
	
	    $dest = array(
	        'o'
	    );
	
	    return str_replace($src, $dest, $string);
	}
	
	/**
	 *
	 * @param string $str
	 * @return string
	 */
    public static function makeUrlFromTitle($str) {
    	$str = str_replace(array(' ') , '_', trim(strtolower(self::translit($str))));
    	return str_replace(array('&', '`', "'", '"', '»', '«', ',', '/') , '', $str);
    }

	public static function getImageUrlResized($imageName, $width, $height, $waterMark = false) {
		$imageUrl = self::getImageUrl( $imageName );
		
		$replication = Image_Replication::getInstance();
		try {
			$image = $replication->getPreview($imageUrl, (int)$width, (int)$height, $waterMark);
		}
		catch (Exception $e) {
			$image = $replication->getPreview( self::getDefaultImage() , (int)$width, (int)$height);
		}
		return $image;
	}

	/**
	 *
	 * @param string $imageName
	 */
	public static function getImageUrl($imageName) {
		if ($imageName) {
			$imageUrl = self::getFileUrl($imageName);
		}
		else {
			$imageUrl = self::getDefaultImage();
		}
		return $imageUrl;
	}
	
	public static function getDefaultImage() {
		return '/images/no_photo.jpg';
	}

	/**
	 *
	 * @param string $param
	 * @param string $id
	 * @param string $email
	 * @return string
	 */
	public static function getSubscribeUrl($param, $id, $email, $cur_user = 'no') {
    $config = Config::getInstance()->default;
    $key = StringFunctions::getSubscribeKey($id, $email, $cur_user);
    $href = "http://{$config->hostname}/news/{$param}/id/{$id}/cur_user/{$cur_user}/key/{$key}";
		return $href;
	}

	/**
	 *
	 * @param string $id
	 * @param string $email
	 * @return string
	 */
	public static function getSubscribeKey($id, $email, $cur_user = 'no') {
		$str = "{$id}{$email}".self::KEY."{$cur_user}";
    $key = md5($str);
    return $key;
	}


	/**
	 *
	 * @param string $fileName
	 */
	public static function getFileUrl($fileName) {
		if (empty($fileName)) {
			return '';
		}
		$folderName = substr($fileName, 0, 2);
		$config = Config::getInstance()->file_transfer;

		return "{$config->hostname}{$config->htdocsPath}/{$folderName}/{$fileName}";
	}

	/**
	 *
	 * @param string $varName
	 * @return string
	 */
	public static function setterName($varName) {
		return 'set'.self::ucfirst($varName);
	}

	/**
	 *
	 * @param string $varName
	 * @return string
	 */
	public static function getterName($varName) {
		return 'get'.self::ucfirst($varName);
	}

	/**
	 *
	 * @param string $varName
	 * @return string
	 */
	public static function setterNameUnderscore($varName) {
		return 'set'.self::underscoreToCamelCase($varName);
	}

	/**
	 *
	 * @param string $varName
	 * @return string
	 */
	public static function getterNameUnderscore($varName) {
		return 'get'.self::underscoreToCamelCase($varName);
	}
	
	/**
	 * парсим строку как csv строку
	 * @todo рецепт возможно коряв, треубет рассмотрения
	 * @param string $string
	 * 
	 * @return array
	 */
	public static function getCsvFromString($string) {
		
		if (!function_exists('str_getcsv')) {
 		  $tmp = fopen("php://memory", "rw");
		  fwrite($tmp, $string);
		  fseek($tmp, 0);
		  $res=fgetcsv($tmp);
		  ftruncate($tmp, 0);
		  fclose($tmp);
		} else {
			$res = str_getcsv($string);
		}
		return $res;
	}

	public static function smartCut($string, $length, $suffix = '...') {
		$oldLength = mb_strlen($string);
		$string = self::wordSplit($string, $length);
		if (mb_strlen($string) < $oldLength) {
			$string .= $suffix;
		}
		return $string;
	}

    /**
     *
     * @param string $string
     * @param int $length
     * @param array|string $delimiters
     * @param bool $cut
     * @return string
     */
    public static function wordSplit($string, $length = 0, $cut = false, $delimiters = array(' ', "\n")) {
        $min_width = mb_strlen($string);
        if($cut OR $min_width < $length) {
            $min_width = min($min_width, $length);
        }
        else {
            foreach ($delimiters as $delimiter) {
                $pos = mb_strpos($string, $delimiter, $length);
                if ($pos!==FALSE AND $pos < $min_width) {
                    $min_width = $pos;
                }
            }
        }

        return mb_substr($string, 0, $min_width);
    }
}